package com.yuanchu.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.order.dao.YoshopOrderAddressDao;
import com.yuanchu.order.dao.YoshopRegionDao;
import com.yuanchu.order.entity.YoshopOrderAddressEntity;
import com.yuanchu.order.entity.YoshopRegionEntity;
import com.yuanchu.order.service.YoshopOrderAddressService;
import com.yuanchu.order.service.YoshopRegionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("yoshopOrderAddressService")
public class YoshopOrderAddressServiceImpl extends ServiceImpl<YoshopOrderAddressDao, YoshopOrderAddressEntity> implements YoshopOrderAddressService {

    @Resource
    private YoshopRegionService orderRegionService;
    @Resource
    private YoshopRegionDao regionDAO;


    public YoshopOrderAddressEntity getAddressByOrderId(Integer orderId) {
        YoshopOrderAddressEntity address = this.getOne(new LambdaQueryWrapper<YoshopOrderAddressEntity>()
                .eq(YoshopOrderAddressEntity::getOrderId, orderId));
        if (address == null){
            return null;
        }
        Map<String, Object> map = regionDAO.getAddressByOrderId(Integer.valueOf(address.getRegionId()));
        address.setRegion(map);
        return address;
    }



    private static Map<String, String> getRegionEntityById(List<YoshopRegionEntity> cityList, int id) {
        Map<String, String> cityInfo = new HashMap<>();
        for (YoshopRegionEntity city : cityList) {
            if (city.getId() == id) {
                // 区
                cityInfo.put("region", city.getName());
                // 根据pid获取上级城市信息
                YoshopRegionEntity parentCity = getParentCity(cityList, city.getPid());
                if (parentCity != null) {
                    // 市
                    cityInfo.put("city", parentCity.getName());
                    // 根据pid获取上上级城市信息
                    YoshopRegionEntity grandParentCity = getParentCity(cityList, parentCity.getPid());
                    if (grandParentCity != null) {
                        // 省
                        cityInfo.put("province", grandParentCity.getName());
                    }
                }
            }
        }
        return cityInfo;
    }

    private static YoshopRegionEntity getParentCity(List<YoshopRegionEntity> cityList, int pid) {
        for (YoshopRegionEntity city : cityList) {
            if (city.getId() == pid) {
                return city;
            }
        }
        return null;
    }




}